<template>
  <view class="chat-bg">
    <!-- 聊天列表 -->
    <scroll-view scroll-y="true" class="chat-list" :scroll-top="data.scrollTop" scroll-with-animation="true" @scrolltoupper="getMoreChatLog">
      <view id="scroll-view-content">
        <block v-for="(item,index) in data.chatList" :key="index">
          <text class="chat-time" v-if="index == 0 || data.chatList[index].timestamp - data.chatList[index - 1].timestamp > 300000">{{item.time}}</text>
          <view class="chat-one" v-if="item.userId != data.curUser.id">
              <image @click="showOtherInfo(item.userId)" class="avatar-chat" :src="data.chatUserAvatar"></image>
              <view class="chat-content">
                <text class="chat-text">{{item.content}}</text>
              </view>
          </view>
          <view class="chat-own" v-else>
            <view class="chat-content">
              <text class="chat-text">{{item.content}}</text>
            </view>
            <image class="avatar-chat" :src="data.curUser.avatar"></image>
          </view>
        </block>
      </view>
     
      
    </scroll-view>
    <!-- 聊天输入框 -->
    <view class="input-view">
          <view class="input-box">
            <input v-model="data.msg" class="m-input" @focus="inputFocus" type="text" adjust-position="false" placeholder="&nbsp;&nbsp;发消息..."/>
          </view>
          <!-- 按钮 -->
          <button class="m-button" @click="send">发送</button>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref,toRefs,onMounted } from 'vue';
import { onShow,onLoad,onUnload,onHide } from '@dcloudio/uni-app'
import helper from '../../common/helper.js'

const data = reactive({
  curUser: uni.getStorageSync("curUser") || null,
  chatUserName:"",
  chatList:[],
  msg:"",
  scrollTop:0,
  scrollViewHeight:0,
  chatUserId:0,
  chatUserAvatar:"",
  id: '',
  total: 0,
  pageSize: 30,
});

onLoad((options)=>{
  console.log(options)
  data.chatUserId = parseInt(options.chatUserId)
  data.chatUserAvatar = options.chatUserAvatar
  data.chatUserName = options.chatUserName
  uni.setNavigationBarTitle({
    title:data.chatUserName
  })
  getChatLog()
  connect()
  onOpen()
  getMsg()
  onClose()
})

function getMoreChatLog(){
  getChatLog()
}

//获取之前的聊天记录
function getChatLog(){
  console.log("获取聊天记录...")
  uni.request({
    url: helper.webUrl + "/chat/getChatLogByUserId",
    method:'GET',
    header:{
      'Content-Type': 'application/x-www-form-urlencoded',
      'token': helper.getToken()
    },
    data: {
      chatUserId: data.chatUserId,
      id: data.id,
      pageSize: data.pageSize
    },
    success: (res) => {
      console.log(res.data);
      let flag = data.chatList.length
      if(res.data.code == 200){
        data.total = res.data.data.total
        let list = res.data.data.record
        data.id = list[list.length-1].id
        for(let i = 0; i < list.length; i++){
          list[i].timestamp = list[i].time
          list[i].time = helper.getDateTime(list[i].time)
          data.chatList.unshift(list[i])
        }   
        //设置滚动轴到底部
        if(flag == 0){
          data.scrollTop+=9999999
        }
      }
    },
    fail: (err) => {
      console.error('请求失败:', err);
    }
  })
}

function connect(){
  uni.connectSocket({
    url: helper.wsUrl+'/chat',
    header: {
    	'content-type': 'application/json',
      'user': helper.getUserId(),
      'Cookie': wx.getStorageSync('cookieKey')
    },
    success: data =>{
      console.log(data)
    }
  })
}

function sendMsg(msg){
  uni.sendSocketMessage({
    data:msg,
    success: (res)=> {
      console.log(res)
    }
  })
}

function showOtherInfo(userId){
  console.log("查看用户")
  uni.navigateTo({
    url:"/subpages/otherInfo/otherInfo?userId="+userId
  })
}

function onOpen(){
  uni.onSocketOpen(function (res) {
    console.log('连接已打开'+res.data)
  })
}

function onClose(){
  uni.onSocketClose(function (res) {
    console.log('连接已关闭'+res.data)
  })
}

function getMsg(){
  uni.onSocketMessage(function (res) {
    console.log('收到服务器内容'+res.data)
    let msg = JSON.parse(res.data)
    let userId = msg.userId
    //是否是当前的聊天窗
      if(userId == data.chatUserId){
        //处理收到的信息
        data.chatList.push({
          userId: data.chatUserId,
          content: msg.content,
          time: new Date()
        })
        data.msg = ""
        // 将滚动轴拉到底部
        data.scrollTop+=9999999
      }  
  })
}

function addChatLog(msg){
  console.log("添加到数据库中...")
  uni.request({
    url: helper.webUrl + "/chat/addChatLog",
    method:'POST',
    header:{
      'Content-Type': 'application/x-www-form-urlencoded',
      'token': helper.getToken()
    },
    data: {
      userId: data.curUser.id,
      chatUserId:data.chatUserId,
      content: data.msg
    },
    success: (res) => {
      console.log(res.data);
    },
    fail: (err) => {
      console.error('请求失败:', err);
    }
  })
}

function inputFocus(){
  // 将滚动轴拉到底部
  data.scrollTop+=9999999
}

function send(){
  console.log(data.msg)
  //判断msg是否空
  if(data.msg == null || data.msg.trim() == ""){
    return
  }
  let json = {
    "userId": data.curUser.id,
    "chatUserId":data.chatUserId,
    "content": data.msg
  }
  console.log(JSON.stringify(json))
  sendMsg(JSON.stringify(json))
  //插入到数据库中
  addChatLog(json)
  // 将信息加入进chatList中
  data.chatList.push({
    userId:data.curUser.id,
    content:data.msg,
    time: new Date(),
  })
  data.msg = ""
  // 将滚动轴拉到底部
  data.scrollTop+=9999999
  
  }
</script>

<style lang="scss" scoped>
.chat-bg{
  background: #f4f4f4;
  width: 100vw;
  height: 93vh;
}
.chat-time{
  display: flex;
  justify-content: center;
  font-size: 15px;
  color: #949494;
  padding: 10px;
}
.chat-list{
  width: 100vw;
  height: 93vh;
  display: flex;
  flex-direction: column;
}
.chat-one,.chat-own{
  display: flex;
  margin-top: 10px;
}
.avatar-chat{
  width: 50px;
  height: 50px;
  margin-left: 10px;
  border-radius: 50px;
}
.chat-own{
  justify-content: flex-end;
  margin: 10px;
}
.chat-content{
  margin: 10px;
  max-width: 70%;
  background: #fff;
  padding: 10px;
  border-radius: 10px;
}
.chat-text{
  font-size: 18px;
  word-wrap: break-word;
  overflow-wrap: break-word;
}
.chat-img{
  width: 100px;
  height: 100px;
  border-radius: 10px;
}
.input-view{
  display: flex;
  justify-content: flex-end;
  width: 100vw;
  height: 7vh;
  align-items: center; /* 垂直居中 */
  background-color: #f4f4f4;
}
.input-box{
  width: 80%;
  height: 60%;
  display: flex;
  align-items: center; /* 垂直居中 */
  margin-left: 2%;
  border-radius: 10px;
  background-color: #fff;
}
.m-input{
 margin-left: 2%;
 width: 100%;
 height: 100%;
}
.m-button{
  width: 15%;
  height: 60%;
  margin: 2%;
  background-color: #89C0FF;
  font-size: 12px;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 20px;
}
</style>
